package com.dcy.system.dao;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import com.dcy.common.base.dao.DcyBaseDao;
import com.dcy.common.constant.RedisConstant;
import com.dcy.system.mapper.ResourceMapper;
import com.dcy.system.model.Resource;
import com.dcy.system.model.RoleRes;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author dcy
 * @since 2022-11-08
 */
@RequiredArgsConstructor
@Service
public class ResourceDao extends DcyBaseDao<ResourceMapper, Resource> {

    @CacheEvict(value = {RedisConstant.REDIS_ROLE_RESOURCE}, allEntries = true, condition = "#result == true")
    @Override
    public boolean save(Resource entity) {
        return super.save(entity);
    }

    @CacheEvict(value = {RedisConstant.REDIS_ROLE_RESOURCE}, allEntries = true, condition = "#result == true")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @CacheEvict(value = {RedisConstant.REDIS_ROLE_RESOURCE}, allEntries = true, condition = "#result == true")
    @Override
    public boolean updateById(Resource entity) {
        return super.updateById(entity);
    }

    /**
     * 根据用户id 查询权限列表
     *
     * @param userId
     * @return
     */
    public List<Resource> selectAuthResourcesListByUserId(String userId) {
        return baseMapper.selectAuthResourcesListByUserId(userId);
    }

    /**
     * 根据角色id查询资源ids
     *
     * @param roleId
     * @return
     */
    public List<String> getResourceIdListByRoleId(String roleId) {
        return SimpleQuery.list(Wrappers.<RoleRes>lambdaQuery().eq(RoleRes::getRoleId, roleId), RoleRes::getResId);
    }

    /**
     * 根据角色id 查询权限标识
     *
     * @param roleId 角色id
     * @return
     */
    @Cacheable(value = RedisConstant.REDIS_ROLE_RESOURCE, key = "#roleId")
    public List<String> selectPermissionListByRoleId(String roleId) {
        return baseMapper.selectPermissionListByRoleId(roleId);
    }
}
